<?php

namespace app\admin\controller;

use app\Request as R;
use app\admin\Validate;
use app\admin\model\AdminUser;
use think\facade\Session;
use app\admin\middleware\Login;
use services\adminUser\AdminUserManger;

class My extends BaseController{



    function update_password(R $req)
    {
        /** @var AdminUser */
        $user =$req->getAttribute('admin_user');
        if($req->isPost()){
            $v  = $this->update_passwordVali();
            $data = $req->only(['new_password','old_password']);
            if(!$v->check($data)){
                return error_json($v->getError());
            }
            /**
             * @var AdminUserManger $adminUserManger
             */
            $adminUserManger = app(AdminUserManger::class);
            if(!$adminUserManger->checkPassword($data['old_password'],$user['password'])){
                return error_json("旧密码不正确");
            }
            $adminUserManger->update($user['id'],[
                'password'=>$data['new_password'],
            ]);
            return success_json("修改成功");
        }
        
        return view('/my/update_password',['user'=>$user]);
    }
    
    function out()
    {
        app(Login::class)->clear();
        return redirect(admin_url('login'));
    }

    function update_passwordVali()
    {
        return new class extends Validate{
            protected $rule = [
                'new_password'  =>  'require|max:20',
                'old_password' =>  'require',
            ];
            protected $message = [
                'old_password.require'=>"旧密码不能为空",
                'new_password.require'=>"新密码不能为空",
                'new_password.max'=>'密码最大长度为20'
            ];
        };
    }


}